package com.buddha.api.controller;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.buddha.api.common.Constants;
import com.buddha.api.common.Result;
import com.buddha.api.dto.MenuDto;
import com.buddha.api.entity.Menu;
import com.buddha.api.entity.RoleMenu;
import com.buddha.api.entity.User;
import com.buddha.api.mapper.UserMapper;
import com.buddha.api.service.impl.MenuServiceImpl;
import com.buddha.api.service.impl.RoleMenuServiceImpl;
import com.buddha.api.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author mybatis-plus
 * @since 2023-07-06
 */
@CrossOrigin(origins = {"*"})
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    UserServiceImpl userService;

    @Autowired
    UserMapper userMapper;

    @Autowired
    RoleMenuServiceImpl roleMenuService;


    @Autowired
    private MenuServiceImpl menuService;

    @PostMapping("/save")
    public Result saveMenu(@Validated @RequestBody Menu menu){
        menu.setCreated(LocalDateTime.now());
        return Result.success(menuService.save(menu));
    }

    @PostMapping("/update")
    public Result updateMenu(@Validated @RequestBody Menu menu){
        menu.setUpdated(LocalDateTime.now());
        userService.clearUserAuthorityByMenu(menu.getId());
        return Result.success(menuService.updateById(menu));
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        int count = menuService.count(new QueryWrapper<Menu>().eq("parent_id", id));
        if (count == 0){
            roleMenuService.remove(new QueryWrapper<RoleMenu>().eq("m_id",id));
            userService.clearUserAuthorityByMenu(id);
            return Result.success(menuService.removeById(id));
        }
        return Result.error(Constants.CODE_500,"请先删除子菜单");
    }
    @GetMapping
    public Result findAll() {
        List<Menu> menus = menuService.tree();
        return Result.success(menus);
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(menuService.getById(id));
    }

    @GetMapping("/page")
    public Result findPage(
            @RequestParam Integer pageNum,
            @RequestParam Integer pageSize) {
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        return Result.success(menuService.page(new Page<>(pageNum, pageSize)));
    }
    @PostMapping("del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids){
        return Result.success(menuService.removeByIds(ids));
    }

    @GetMapping("/nav")
    public Result nav(Principal principal){
        User user = userService.findByUsername(principal.getName());
        String authorityInfo = userService.getUserAuthorityInfo(user.getId());
        String[] authorityInfoArray = StringUtils.tokenizeToStringArray(authorityInfo, ",");
        List<MenuDto> navs = menuService.getCurrentUserNav();
        return Result.success(MapUtil.builder()
                .put("authorities", authorityInfoArray)
                .put("nav", navs)
                .map());
    }

}

